﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SanQiOther.Models;

namespace SanQiOther.Controllers
{
    public class LoginController : Controller
    {
        RewardDbContext db = new RewardDbContext();
        public ActionResult Login()
        {
            ViewBag.SystemName = AppConfig.SYSNAME;
            return View();
        }

        [HttpPost]
        public ActionResult Login(string BackUrl, LoginViewModel login)
        {
            if (ModelState.IsValid)
            {
                var user = db.v_user.FirstOrDefault(u => u.userAccount == login.UserAccount);

                if (user != null)
                {
                    if (user.userpwd == EncryptHelper.Md5Encrypt(login.UserPwd))
                    {
                        Session[AppConfig.SESSION_USER_ISLOGIN] = "1";
                        Session[AppConfig.SESSION_USER_NAME] = user.userName;
                        Session[AppConfig.SESSION_USER_ACCOUNT] = user.userAccount;
                        Session[AppConfig.SESSION_USER_ROLE_ID] = user.roleID;
                        Session[AppConfig.SESSION_USER_BH] = user.userbh;
                        Session[AppConfig.SESSION_USER_DEPT] = user.dept;
                        Session[AppConfig.SESSION_USER_ID] = user.ID;

                        if (string.IsNullOrEmpty(BackUrl))
                        {
                            return RedirectToRoute(new { controller = "Login", action = "Welcome" });
                        }
                        else
                        {
                            return new RedirectResult(BackUrl);
                        }
                    }
                    else
                    {
                        ViewBag.Error = "密码不正确";
                    }
                }
                else
                {
                    ViewBag.Error = "用户不存在";
                }
            }

            return View(login);
        }

        public ActionResult Welcome()
        {
            return View();
        }
    }
}